package com.cold.legendary.bprocess.trigger.helper;

import com.cold.legendary.bprocess.common.constance.BErrorCodeEnum;
import com.cold.legendary.bprocess.common.exception.BProcessException;
import com.cold.legendary.bprocess.common.utils.ValidateBeanUtils;
import com.cold.legendary.bprocess.context.run.BContext;
import com.cold.legendary.bprocess.db.model.TbProcessRequest;
import com.cold.legendary.bprocess.db.repository.ProcessRequestRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author cold
 * @since 2023/3/10
 */
@Slf4j
@Component
public class ProcessRequestCheckHelper {

    @Resource
    private ProcessRequestRepository processRequestRepository;

    /**
     * 业务校验
     *
     * @param bContext 上下文
     * @return 流程请求对象
     */
    public TbProcessRequest checkProcessRequest(BContext bContext) {
        //校验参数合法性
        ValidateBeanUtils.validateAnnotation(bContext);

        if (StringUtils.isEmpty(bContext.getPointId())) {
            throw new BProcessException(BErrorCodeEnum.SYS_POINTID_NONE_ERROR);
        }

        String bizId = bContext.getBizId();
        String merchantId = bContext.getMerchantId();
        String processId = bContext.getProcessId();

        //先进行幂等判断
        TbProcessRequest qryProcessRequest = processRequestRepository.queryTbProcessRequest(bizId, merchantId, processId);
        if (null == qryProcessRequest) {
            log.info("流程请求记录不存在!bizId={}, merchantId={},processId={}", bizId, merchantId, processId);
            throw new BProcessException(BErrorCodeEnum.SYS_PROCESS_REQUEST_NONE_ERROR);
        }
        return qryProcessRequest;
    }
}
